﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PB.Airsoft.Business.Account;
using PB.Airsoft.Business.Account.Interfaces;
using PB.Airsoft.NHibernateWrapper;
using PB.Airsoft.Core;
using NHibernate.Criterion;
using PB.Airsoft.Business.Account.Entities;
using System.Configuration;
using PB.Airsoft.Core.Unity;

namespace PB.Airsoft.Provider.NHibernate.Account
{
    public class NHibernateAccountProvider : AccountProvider
    {
        private ISessionManager CreateSessionManager(bool readOnly)
        {
            return new SessionManager(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString, readOnly);
        }

        public override IUserAccount GetUserAccountByEmail(string email)
        {
            using (var sm = CreateSessionManager(true))
            {
                var criteria = sm.Session.CreateCriteria(IoC.GetRegisteredType<IUserAccount>());
                criteria.Add(Expression.Eq("Email", email));
                return criteria.UniqueResult<IUserAccount>();
            }
        }

        public override void CreateUserAccount(IUserAccount userAccount)
        {
            using (var sm = CreateSessionManager(false))
            {
                sm.Session.Save(userAccount);
                sm.Commit();
            }
        }
    }
}
